#include "log/log.h"
#include "cJSON/cJSON.h"
#include <stdlib.h>
#include <string.h>
#include "app_common.h"

/*
字符数组:  1 2 4 XXabcd
json字符串: {"conn_type": 1, "id": "5858", "msg": "61626364"}
*/
char *app_message_charsToJson(char *chars, int len) {
    // 从chars中解析出conn_type, id_len, msg_len, id, msg
    int conn_type = (int)chars[0];
    int id_len = (int)chars[1];
    int msg_len = (int)chars[2];
    // 检查len
    if (len != 3 + id_len + msg_len) {
        log_error("字符数组的长度不正确");
        return NULL;
    }
    char id[id_len];
    char msg[msg_len];
    memcpy(id, chars+3, id_len);
    memcpy(msg, chars+3+id_len, msg_len);


    // 生成id和msg的16进制字符串id_hex和msg_hex
    char *id_hex = app_common_charsToHexstr(id, id_len);
    char *msg_hex = app_common_charsToHexstr(msg, msg_len);

    // 生成json消息
    cJSON *root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, "conn_type", conn_type);
    cJSON_AddStringToObject(root, "id", id_hex);
    cJSON_AddStringToObject(root, "msg", msg_hex);
    char *json = cJSON_PrintUnformatted(root);

    // 释放内存
    cJSON_Delete(root);
    free(id_hex);
    free(msg_hex);

    // 返回生成的json消息
    return json;
}

/*
字符数组:  1 2 4 XXabcd
json字符串: {"conn_type": 1, "id": "5858", "msg": "61626364"}
*/
int app_message_jsonToChars(char *json, char *chars_buf, int buf_size) {
    // 解析json得到conn_type, id_hexstr, msg_hexstr
    cJSON *root = cJSON_Parse(json);
    int conn_type = cJSON_GetObjectItem(root, "conn_type")->valueint;
    char *id_hexstr = cJSON_GetObjectItem(root, "id")->valuestring;
    char *msg_hexstr = cJSON_GetObjectItem(root, "msg")->valuestring;

    // 将id_hexstr和msg_hexstr转换为对应的字符数组id和msg，并得到id_len和msg_len
    int id_len = 0;
    int msg_len = 0;
    char *id = app_common_hexstrToChars(id_hexstr, &id_len);
    char *msg = app_common_hexstrToChars(msg_hexstr, &msg_len);

    // 计算字符数组的长度
    int chars_len = 3 + id_len + msg_len;
    // 检查buf_size
    if (buf_size < chars_len) {
        log_error("字符数组容器大小不足");
        return -1;
    }

    // 将conn_type，id_len,msg_len, id和msg添加到chars_buf中 1 2 4 XXabcd
    chars_buf[0] = (char)conn_type;
    chars_buf[1] = (char)id_len;
    chars_buf[2] = (char)msg_len;
    memcpy(chars_buf+3, id, id_len);
    memcpy(chars_buf+3+id_len, msg, msg_len);

    // 释放内存
    cJSON_Delete(root);
    free(id);
    free(msg);

    // 返回字符数组的长度
    return chars_len;
}